﻿using CTP.CRM.Core.CurrentUs;
using CTP.CRM.Core.SqlSugar.Entitys;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CTP.CRM.Repository
{
    /// <summary>
    /// Sqlsugar 上下文对象
    /// </summary>
    public class DataBaseContext
    {
        #region 审计属性自动赋值

        /// <summary>
        /// 当执行数据库操作之前，会触发这个事件
        /// </summary>
        /// <param name="oldValue"></param>
        /// <param name="entityInfo"></param>
        /// <exception cref="Exception"></exception>
        public static void OnExcutingAction(object oldValue, DataFilterModel entityInfo)
        {
            //过滤掉 "v_" 开头的表
            if (entityInfo.EntityColumnInfo.DbTableName.StartsWith("v_", StringComparison.OrdinalIgnoreCase))
                throw new Exception("非法的操作，不允许编辑映射表");

            //新增
            if (entityInfo.OperationType == DataFilterType.InsertByObject)
            {
                if (entityInfo.PropertyName == nameof(ICreateBaicEntity.CreateTime))
                    entityInfo.SetValue(DateTime.Now);
                //外部用户不操作
                if (entityInfo.PropertyName == nameof(ICreateBaicEntity.CreateUserId)
                    && (CurrentUserRequest.CurrentUser.ExternalMainId == null || CurrentUserRequest.CurrentUser.ExternalMainId <= 0))
                {
                    entityInfo.SetValue(CurrentUserRequest.CurrentUser.UserId);
                }
            }
            //修改
            else if (entityInfo.OperationType == DataFilterType.UpdateByObject)
            {
                if (entityInfo.PropertyName == nameof(IUpdateBasicEntity.UpdateTime))
                    entityInfo.SetValue(DateTime.Now);
                //外部用户不操作
                else if (entityInfo.PropertyName == nameof(IUpdateBasicEntity.UpdateUserId)
                    && (CurrentUserRequest.CurrentUser.ExternalMainId == null || CurrentUserRequest.CurrentUser.ExternalMainId <= 0))
                {
                    entityInfo.SetValue(CurrentUserRequest.CurrentUser.UserId);
                }
                //删除
                else if (entityInfo.PropertyName == nameof(IDeleteBasicEntity.IsDeleted))
                {
                    var currentType = entityInfo.EntityValue.GetType();
                    bool.TryParse(currentType.GetProperty(entityInfo.PropertyName)?.GetValue(entityInfo.EntityValue)?.ToString(), out bool isdelete);
                    if (isdelete)
                    {
                        currentType.GetProperty(nameof(IDeleteBasicEntity.DeleteUserId))
                            ?.SetValue(entityInfo.EntityValue, CurrentUserRequest.CurrentUser.UserId);
                        currentType.GetProperty(nameof(IDeleteBasicEntity.DeleteTime))?.SetValue(entityInfo.EntityValue, DateTime.Now);
                    }
                }
            }
        }

        #endregion 审计属性自动赋值
    }
}
